// 文档转换服务 - 将Office文档转换为HTML格式
const mammoth = require('mammoth');
const fs = require('fs');
const path = require('path');
const database = require('../../src/config/database');
const pool = database.default || database.pool;

class DocumentConversionService {
  // 转换Word文档为HTML
  async convertWordToHtml(filePath, originalName) {
    try {
      console.log('开始转换Word文档:', originalName);
      
      // 配置mammoth转换选项
      const options = {
        path: filePath,
        styleMap: [
          // 标题样式映射
          "p[style-name='Title'] => h1.document-title",
          "p[style-name='Heading 1'] => h1",
          "p[style-name='Heading 2'] => h2", 
          "p[style-name='Heading 3'] => h3",
          "p[style-name='Heading 4'] => h4",
          "p[style-name='Heading 5'] => h5",
          "p[style-name='Heading 6'] => h6",
          // 列表样式映射
          "p[style-name='List Paragraph'] => li",
          // 引用样式映射
          "p[style-name='Quote'] => blockquote",
          // 代码样式映射
          "p[style-name='Code'] => pre",
          // 强调样式
          "r[style-name='Strong'] => strong",
          "r[style-name='Emphasis'] => em"
        ],
        convertImage: mammoth.images.imgElement(function(image) {
          // 处理图片转换
          return image.read("base64").then(function(imageBuffer) {
            return {
              src: "data:" + image.contentType + ";base64," + imageBuffer
            };
          });
        })
      };
      
      // 使用mammoth转换docx文件
      const result = await mammoth.convertToHtml(options);
      
      if (result.messages && result.messages.length > 0) {
        console.log('转换警告:', result.messages);
      }
      
      // 清理和优化HTML
      const cleanHtml = this.cleanHtml(result.value);
      
      console.log('Word文档转换成功:', originalName);
      return {
        success: true,
        html: cleanHtml,
        warnings: result.messages || []
      };
    } catch (error) {
      console.error('Word文档转换失败:', error);
      return {
        success: false,
        error: error.message
      };
    }
  }

  // 转换Excel文档为HTML表格
  async convertExcelToHtml(filePath, originalName) {
    try {
      console.log('开始转换Excel文档:', originalName);
      
      // 获取文件统计信息
      const stats = fs.existsSync(filePath) ? fs.statSync(filePath) : null;
      const fileSize = stats ? (stats.size / 1024).toFixed(1) : '未知';
      
      // 对于Excel文件，我们提供一个美观的预览界面
      const html = `
        <style>
          .excel-preview {
            max-width: 600px;
            margin: 0 auto;
            padding: 24px;
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
            border-radius: 12px;
            box-shadow: 0 8px 32px rgba(0,0,0,0.1);
            text-align: center;
          }
          .excel-icon {
            font-size: 64px;
            margin-bottom: 20px;
            animation: bounce 2s infinite;
          }
          @keyframes bounce {
            0%, 20%, 50%, 80%, 100% { transform: translateY(0); }
            40% { transform: translateY(-10px); }
            60% { transform: translateY(-5px); }
          }
          .excel-title {
            color: #1890ff;
            font-size: 24px;
            font-weight: 600;
            margin-bottom: 12px;
            word-break: break-word;
          }
          .excel-subtitle {
            color: #666;
            font-size: 16px;
            margin-bottom: 20px;
          }
          .excel-description {
            color: #999;
            font-size: 14px;
            line-height: 1.6;
            margin-bottom: 24px;
            padding: 0 20px;
          }
          .excel-features {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 16px;
            margin: 24px 0;
          }
          .excel-feature {
            background: rgba(255,255,255,0.8);
            padding: 16px;
            border-radius: 8px;
            backdrop-filter: blur(10px);
          }
          .excel-feature-icon {
            font-size: 24px;
            margin-bottom: 8px;
          }
          .excel-feature-title {
            font-weight: 600;
            color: #333;
            margin-bottom: 4px;
          }
          .excel-feature-desc {
            font-size: 12px;
            color: #666;
          }
          .excel-info {
            background: rgba(255,255,255,0.9);
            padding: 16px;
            border-radius: 8px;
            margin-top: 20px;
            backdrop-filter: blur(10px);
          }
          .excel-stats {
            display: flex;
            justify-content: center;
            gap: 24px;
            margin-top: 16px;
            flex-wrap: wrap;
          }
          .excel-stat {
            display: flex;
            align-items: center;
            gap: 6px;
            font-size: 14px;
            color: #666;
          }
        </style>
        <div class="excel-preview">
          <div class="excel-icon">📊</div>
          <h3 class="excel-title">${originalName}</h3>
          <p class="excel-subtitle">Excel 电子表格文档</p>
          <p class="excel-description">
            这是一个Excel电子表格文档，包含数据表格、图表、公式等丰富内容。
            为了获得最佳的查看和编辑体验，建议下载后使用专业的表格软件打开。
          </p>
          
          <div class="excel-features">
            <div class="excel-feature">
              <div class="excel-feature-icon">📈</div>
              <div class="excel-feature-title">数据分析</div>
              <div class="excel-feature-desc">支持复杂的数据计算和分析</div>
            </div>
            <div class="excel-feature">
              <div class="excel-feature-icon">📊</div>
              <div class="excel-feature-title">图表展示</div>
              <div class="excel-feature-desc">丰富的图表类型和可视化</div>
            </div>
            <div class="excel-feature">
              <div class="excel-feature-icon">🔢</div>
              <div class="excel-feature-title">公式计算</div>
              <div class="excel-feature-desc">强大的公式和函数支持</div>
            </div>
          </div>
          
          <div class="excel-info">
            <div style="font-size: 14px; color: #333; margin-bottom: 8px;">
              <strong>💡 推荐打开方式</strong>
            </div>
            <div style="font-size: 13px; color: #666; line-height: 1.5;">
              • Microsoft Excel (推荐)<br>
              • WPS 表格<br>
              • Google Sheets (在线)<br>
              • LibreOffice Calc (免费)
            </div>
            
            <div class="excel-stats">
              <div class="excel-stat">
                <span>📁</span>
                <span>文件大小: ${fileSize} KB</span>
              </div>
              <div class="excel-stat">
                <span>📅</span>
                <span>Excel 格式</span>
              </div>
              <div class="excel-stat">
                <span>🔒</span>
                <span>安全预览</span>
              </div>
            </div>
          </div>
        </div>
      `;
      
      return {
        success: true,
        html: html,
        isPreview: true
      };
    } catch (error) {
      console.error('Excel文档转换失败:', error);
      return {
        success: false,
        error: error.message
      };
    }
  }

  // 转换PowerPoint文档为HTML
  async convertPowerPointToHtml(filePath, originalName) {
    try {
      console.log('开始转换PowerPoint文档:', originalName);
      
      // 获取文件统计信息
      const stats = fs.existsSync(filePath) ? fs.statSync(filePath) : null;
      const fileSize = stats ? (stats.size / 1024).toFixed(1) : '未知';
      
      // 获取文件的相对路径用于预览
      const relativePath = path.relative(process.cwd(), filePath);
      const webPath = '/' + relativePath.replace(/\\/g, '/');
      
      // 对于PPT文件，提供内嵌预览和美观的界面
      const html = `
        <style>
          .ppt-container {
            width: 100%;
            max-width: 900px;
            margin: 0 auto;
            border: 1px solid #d9d9d9;
            border-radius: 12px;
            overflow: hidden;
            box-shadow: 0 4px 16px rgba(0,0,0,0.1);
            background: #fff;
          }
          .ppt-header {
            padding: 16px 20px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            display: flex;
            align-items: center;
            justify-content: space-between;
          }
          .ppt-title-section {
            display: flex;
            align-items: center;
            gap: 12px;
            flex: 1;
          }
          .ppt-icon {
            font-size: 24px;
          }
          .ppt-name {
            font-weight: 600;
            font-size: 16px;
            word-break: break-word;
          }
          .ppt-actions {
            display: flex;
            gap: 12px;
            align-items: center;
          }
          .ppt-action {
            padding: 6px 12px;
            background: rgba(255,255,255,0.2);
            border: 1px solid rgba(255,255,255,0.3);
            border-radius: 6px;
            text-decoration: none;
            color: white;
            font-size: 12px;
            font-weight: 500;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            gap: 4px;
          }
          .ppt-action:hover {
            background: rgba(255,255,255,0.3);
            color: white;
            transform: translateY(-1px);
          }
          .ppt-preview-area {
            height: 500px;
            background: #f8f9fa;
            display: flex;
            align-items: center;
            justify-content: center;
            position: relative;
          }
          .ppt-preview {
            max-width: 700px;
            margin: 0 auto;
            padding: 24px;
            text-align: center;
            color: #333;
          }
          .ppt-preview-icon {
            font-size: 64px;
            margin-bottom: 20px;
            animation: slideIn 1.5s ease-out;
            color: #667eea;
          }
          @keyframes slideIn {
            0% { transform: translateX(-100px); opacity: 0; }
            100% { transform: translateX(0); opacity: 1; }
          }
          .ppt-preview-title {
            color: #333;
            font-size: 24px;
            font-weight: 600;
            margin-bottom: 12px;
            word-break: break-word;
          }
          .ppt-subtitle {
            color: #666;
            font-size: 16px;
            margin-bottom: 20px;
          }
          .ppt-description {
            color: #666;
            font-size: 14px;
            line-height: 1.6;
            margin-bottom: 24px;
            padding: 0 20px;
          }
          .ppt-slides {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 16px;
            margin: 24px 0;
          }
          .ppt-slide {
            background: #fff;
            padding: 20px 16px;
            border-radius: 8px;
            border: 1px solid #e8e8e8;
            transition: transform 0.3s ease;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
          }
          .ppt-slide:hover {
            transform: translateY(-5px);
            box-shadow: 0 4px 16px rgba(0,0,0,0.15);
          }
          .ppt-slide-icon {
            font-size: 32px;
            margin-bottom: 12px;
          }
          .ppt-slide-title {
            font-weight: 600;
            color: #333;
            margin-bottom: 6px;
            font-size: 14px;
          }
          .ppt-slide-desc {
            font-size: 12px;
            color: #666;
          }
          .ppt-info {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 8px;
            margin-top: 20px;
            border: 1px solid #e8e8e8;
          }
          .ppt-apps {
            display: flex;
            justify-content: center;
            gap: 20px;
            margin: 16px 0;
            flex-wrap: wrap;
          }
          .ppt-app {
            display: flex;
            align-items: center;
            gap: 8px;
            background: #fff;
            padding: 8px 12px;
            border-radius: 20px;
            font-size: 13px;
            color: #333;
            border: 1px solid #e8e8e8;
          }
          .ppt-stats {
            display: flex;
            justify-content: center;
            gap: 24px;
            margin-top: 16px;
            flex-wrap: wrap;
          }
          .ppt-stat {
            display: flex;
            align-items: center;
            gap: 6px;
            font-size: 14px;
            color: #666;
          }
        </style>
        <div class="ppt-container">
          <div class="ppt-header">
            <div class="ppt-title-section">
              <span class="ppt-icon">📽️</span>
              <span class="ppt-name">${originalName}</span>
            </div>
            <div class="ppt-actions">
              <a href="${webPath}" target="_blank" class="ppt-action">
                <span>🔗</span>
                <span>新窗口</span>
              </a>
              <a href="${webPath}" download="${originalName}" class="ppt-action">
                <span>⬇️</span>
                <span>下载</span>
              </a>
            </div>
          </div>
          <div class="ppt-preview-area">
            <div class="ppt-preview">
              <div class="ppt-preview-icon">📽️</div>
              <h3 class="ppt-preview-title">PowerPoint 演示文稿</h3>
              <p class="ppt-subtitle">专业的幻灯片演示文档</p>
              <p class="ppt-description">
                这是一个PowerPoint演示文稿，包含幻灯片、动画效果、图表和多媒体内容。
                为了体验完整的演示效果和交互功能，建议下载后使用专业的演示软件打开。
              </p>
          
          <div class="ppt-slides">
            <div class="ppt-slide">
              <div class="ppt-slide-icon">🎨</div>
              <div class="ppt-slide-title">精美设计</div>
              <div class="ppt-slide-desc">专业的幻灯片设计和布局</div>
            </div>
            <div class="ppt-slide">
              <div class="ppt-slide-icon">🎬</div>
              <div class="ppt-slide-title">动画效果</div>
              <div class="ppt-slide-desc">丰富的切换和动画效果</div>
            </div>
            <div class="ppt-slide">
              <div class="ppt-slide-icon">📊</div>
              <div class="ppt-slide-title">图表数据</div>
              <div class="ppt-slide-desc">可视化的数据展示</div>
            </div>
            <div class="ppt-slide">
              <div class="ppt-slide-icon">🎵</div>
              <div class="ppt-slide-title">多媒体</div>
              <div class="ppt-slide-desc">音频、视频等多媒体内容</div>
            </div>
          </div>
              
              <div class="ppt-info">
                <div style="font-size: 16px; color: #333; margin-bottom: 12px; font-weight: 600;">
                  🚀 推荐打开方式
                </div>
                
                <div class="ppt-apps">
                  <div class="ppt-app">
                    <span>🏢</span>
                    <span>Microsoft PowerPoint</span>
                  </div>
                  <div class="ppt-app">
                    <span>📱</span>
                    <span>WPS 演示</span>
                  </div>
                  <div class="ppt-app">
                    <span>🌐</span>
                    <span>Google Slides</span>
                  </div>
                  <div class="ppt-app">
                    <span>🆓</span>
                    <span>LibreOffice Impress</span>
                  </div>
                </div>
                
                <div class="ppt-stats">
                  <div class="ppt-stat">
                    <span>📁</span>
                    <span>文件大小: ${fileSize} KB</span>
                  </div>
                  <div class="ppt-stat">
                    <span>🎯</span>
                    <span>演示文稿</span>
                  </div>
                  <div class="ppt-stat">
                    <span>✨</span>
                    <span>交互体验</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      `;
      
      return {
        success: true,
        html: html,
        isPreview: true
      };
    } catch (error) {
      console.error('PowerPoint文档转换失败:', error);
      return {
        success: false,
        error: error.message
      };
    }
  }

  // 转换PDF文档为HTML
  async convertPdfToHtml(filePath, originalName) {
    try {
      console.log('开始处理PDF文档:', originalName);
      
      // 获取文件统计信息
      const stats = fs.existsSync(filePath) ? fs.statSync(filePath) : null;
      const fileSize = stats ? (stats.size / 1024).toFixed(1) : '未知';
      
      // 对于PDF文件，我们提供内嵌预览
      const relativePath = path.relative(process.cwd(), filePath);
      const webPath = '/' + relativePath.replace(/\\/g, '/');
      
      const html = `
        <style>
          .pdf-container {
            width: 100%;
            height: 650px;
            border: 1px solid #d9d9d9;
            border-radius: 12px;
            overflow: hidden;
            box-shadow: 0 4px 16px rgba(0,0,0,0.1);
            background: #fff;
          }
          .pdf-header {
            padding: 16px 20px;
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
            border-bottom: 1px solid #e8e8e8;
            display: flex;
            align-items: center;
            justify-content: space-between;
          }
          .pdf-title {
            display: flex;
            align-items: center;
            gap: 12px;
            flex: 1;
          }
          .pdf-icon {
            font-size: 24px;
            color: #ff4757;
          }
          .pdf-name {
            font-weight: 600;
            color: #333;
            font-size: 16px;
            word-break: break-word;
          }
          .pdf-actions {
            display: flex;
            gap: 12px;
            align-items: center;
          }
          .pdf-action {
            padding: 6px 12px;
            background: rgba(255,255,255,0.9);
            border: 1px solid #d9d9d9;
            border-radius: 6px;
            text-decoration: none;
            color: #1890ff;
            font-size: 12px;
            font-weight: 500;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            gap: 4px;
          }
          .pdf-action:hover {
            background: #1890ff;
            color: white;
            transform: translateY(-1px);
            box-shadow: 0 2px 8px rgba(24,144,255,0.3);
          }
          .pdf-viewer {
            width: 100%;
            height: calc(100% - 70px);
            border: none;
            background: #f8f9fa;
          }
          .pdf-embed {
            width: 100%;
            height: 100%;
            border: none;
          }
          .pdf-stats {
            position: absolute;
            top: 16px;
            right: 140px;
            display: flex;
            gap: 12px;
            font-size: 11px;
            color: #666;
          }
          .pdf-stat {
            background: rgba(255,255,255,0.8);
            padding: 4px 8px;
            border-radius: 12px;
            backdrop-filter: blur(5px);
          }
          .pdf-loading {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            color: #666;
            font-size: 14px;
            display: none;
          }
        </style>
        <div class="pdf-container">
          <div class="pdf-header">
            <div class="pdf-title">
              <span class="pdf-icon">📄</span>
              <span class="pdf-name">${originalName}</span>
            </div>
            <div class="pdf-stats">
              <div class="pdf-stat">📁 ${fileSize} KB</div>
              <div class="pdf-stat">📄 PDF</div>
            </div>
            <div class="pdf-actions">
              <a href="${webPath}" target="_blank" class="pdf-action">
                <span>🔗</span>
                <span>新窗口</span>
              </a>
              <a href="${webPath}" download="${originalName}" class="pdf-action">
                <span>⬇️</span>
                <span>下载</span>
              </a>
            </div>
          </div>
          <div class="pdf-loading">正在加载PDF文档...</div>
          <object 
            data="${webPath}#toolbar=1&navpanes=1&scrollbar=1&view=FitH" 
            type="application/pdf"
            class="pdf-viewer"
            title="${originalName}"
          >
            <embed 
              src="${webPath}#toolbar=1&navpanes=1&scrollbar=1&view=FitH" 
              type="application/pdf"
              class="pdf-embed"
            />
            <div style="padding: 40px; text-align: center; color: #666;">
              <div style="font-size: 48px; margin-bottom: 16px;">📄</div>
              <div style="font-size: 16px; margin-bottom: 12px;">PDF预览不可用</div>
              <div style="font-size: 14px; margin-bottom: 20px;">您的浏览器不支持PDF内嵌预览</div>
              <a href="${webPath}" target="_blank" style="display: inline-block; padding: 8px 16px; background: #1890ff; color: white; text-decoration: none; border-radius: 4px;">
                在新窗口中打开PDF
              </a>
            </div>
          </object>
        </div>
        <script>
          // 显示加载提示
          document.querySelector('.pdf-loading').style.display = 'block';
          
          // 3秒后如果还在加载，显示提示
          setTimeout(() => {
            const loading = document.querySelector('.pdf-loading');
            if (loading.style.display !== 'none') {
              loading.innerHTML = 'PDF文档较大，正在加载中...';
            }
          }, 9090);
        </script>
      `;
      
      return {
        success: true,
        html: html,
        isEmbedded: true
      };
    } catch (error) {
      console.error('PDF文档处理失败:', error);
      return {
        success: false,
        error: error.message
      };
    }
  }

  // 转换文本文档为HTML
  async convertTextToHtml(filePath, originalName) {
    try {
      console.log('开始转换文本文档:', originalName);
      
      const content = fs.readFileSync(filePath, 'utf8');
      
      // 检测文本内容类型并相应处理
      const isCode = this.detectCodeContent(content, originalName);
      const processedContent = this.processTextContent(content, isCode);
      
      // 将文本转换为HTML，保持格式
      const html = `
        <style>
          .text-document {
            font-family: ${isCode ? "'Courier New', 'Monaco', 'Menlo', monospace" : "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif"};
            line-height: 1.6;
            color: #333;
            background-color: #fafafa;
            border-radius: 8px;
            padding: 20px;
            border: 1px solid #e8e8e8;
          }
          .text-document-header {
            display: flex;
            align-items: center;
            margin-bottom: 16px;
            padding-bottom: 12px;
            border-bottom: 2px solid #e8e8e8;
          }
          .text-document-icon {
            font-size: 24px;
            margin-right: 12px;
          }
          .text-document-title {
            font-size: 18px;
            font-weight: 600;
            color: #1890ff;
            margin: 0;
          }
          .text-document-content {
            white-space: pre-wrap;
            word-wrap: break-word;
            margin: 0;
            ${isCode ? 'background-color: #f6f8fa; padding: 16px; border-radius: 6px; border: 1px solid #d0d7de; overflow-x: auto;' : ''}
          }
          .text-document-stats {
            margin-top: 16px;
            padding-top: 12px;
            border-top: 1px solid #e8e8e8;
            font-size: 12px;
            color: #666;
            display: flex;
            gap: 16px;
          }
        </style>
        <div class="text-document">
          <div class="text-document-header">
            <span class="text-document-icon">${isCode ? '💻' : '📄'}</span>
            <h4 class="text-document-title">${originalName}</h4>
          </div>
          <pre class="text-document-content">${processedContent}</pre>
          <div class="text-document-stats">
            <span>📊 ${content.split('\n').length} 行</span>
            <span>📝 ${content.length} 字符</span>
            <span>📁 ${(content.length / 1024).toFixed(1)} KB</span>
            ${isCode ? '<span>💻 代码文件</span>' : '<span>📄 文本文件</span>'}
          </div>
        </div>
      `;
      
      return {
        success: true,
        html: html
      };
    } catch (error) {
      console.error('文本文档转换失败:', error);
      return {
        success: false,
        error: error.message
      };
    }
  }

  // 检测是否为代码内容
  detectCodeContent(content, filename) {
    // 根据文件扩展名判断
    const codeExtensions = ['.js', '.ts', '.jsx', '.tsx', '.py', '.java', '.cpp', '.c', '.h', '.css', '.html', '.xml', '.json', '.sql', '.php', '.rb', '.go', '.rs', '.swift', '.kt'];
    const hasCodeExtension = codeExtensions.some(ext => filename.toLowerCase().endsWith(ext));
    
    if (hasCodeExtension) return true;
    
    // 根据内容特征判断
    const codePatterns = [
      /function\s+\w+\s*\(/,
      /class\s+\w+/,
      /import\s+.*from/,
      /\#include\s*</,
      /def\s+\w+\s*\(/,
      /public\s+class/,
      /\<\?php/,
      /\{\s*".*":\s*.*\}/,
      /SELECT\s+.*FROM/i,
      /\<html\>/i,
      /\<\!DOCTYPE/i
    ];
    
    return codePatterns.some(pattern => pattern.test(content));
  }

  // 处理文本内容
  processTextContent(content, isCode) {
    let processed = this.escapeHtml(content);
    
    if (!isCode) {
      // 对于普通文本，添加一些基本的格式化
      processed = processed
        .replace(/^(#{1,6})\s+(.+)$/gm, (match, hashes, title) => {
          const level = hashes.length;
          return `<h${level} style="color: #1890ff; margin: 16px 0 8px 0;">${title}</h${level}>`;
        })
        .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
        .replace(/\*(.*?)\*/g, '<em>$1</em>')
        .replace(/`(.*?)`/g, '<code style="background-color: #f6f8fa; padding: 2px 4px; border-radius: 3px;">$1</code>');
    }
    
    return processed;
  }

  // 主转换方法
  async convertDocument(filePath, originalName, mimeType) {
    try {
      console.log('开始转换文档:', originalName, mimeType);
      
      let result;
      
      // 根据文件类型选择转换方法
      if (mimeType === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' || 
          mimeType === 'application/msword') {
        // Word文档
        result = await this.convertWordToHtml(filePath, originalName);
      } else if (mimeType === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || 
                 mimeType === 'application/vnd.ms-excel') {
        // Excel文档
        result = await this.convertExcelToHtml(filePath, originalName);
      } else if (mimeType === 'application/vnd.openxmlformats-officedocument.presentationml.presentation' || 
                 mimeType === 'application/vnd.ms-powerpoint') {
        // PowerPoint文档
        result = await this.convertPowerPointToHtml(filePath, originalName);
      } else if (mimeType === 'application/pdf') {
        // PDF文档
        result = await this.convertPdfToHtml(filePath, originalName);
      } else if (mimeType === 'text/plain') {
        // 文本文档
        result = await this.convertTextToHtml(filePath, originalName);
      } else {
        // 不支持的文件类型
        result = {
          success: false,
          error: `不支持的文件类型: ${mimeType}`
        };
      }
      
      return result;
    } catch (error) {
      console.error('文档转换失败:', error);
      return {
        success: false,
        error: error.message
      };
    }
  }

  // 保存转换结果到数据库
  async saveConversionResult(userId, fileId, html, status = 'completed', errorMessage = null) {
    try {
      // 先检查是否已存在
      const checkQuery = `
        SELECT id FROM document_conversions 
        WHERE original_file_id = $1
      `;
      
      const checkResult = await pool.query(checkQuery, [fileId]);
      
      let query, values;
      
      if (checkResult.rows.length > 0) {
        // 更新现有记录
        query = `
          UPDATE document_conversions 
          SET converted_html = $1, conversion_status = $2, error_message = $3, updated_at = CURRENT_TIMESTAMP
          WHERE original_file_id = $4
          RETURNING *
        `;
        values = [html, status, errorMessage, fileId];
      } else {
        // 插入新记录
        query = `
          INSERT INTO document_conversions (user_id, original_file_id, converted_html, conversion_status, error_message)
          VALUES ($1, $2, $3, $4, $5)
          RETURNING *
        `;
        values = [userId, fileId, html, status, errorMessage];
      }
      
      const result = await pool.query(query, values);
      
      return {
        success: true,
        data: result.rows[0]
      };
    } catch (error) {
      console.error('保存转换结果失败:', error);
      return {
        success: false,
        error: error.message
      };
    }
  }

  // 获取转换结果
  async getConversionResult(fileId) {
    try {
      const query = `
        SELECT * FROM document_conversions 
        WHERE original_file_id = $1
        ORDER BY created_at DESC
        LIMIT 1
      `;
      
      const result = await pool.query(query, [fileId]);
      
      if (result.rows.length === 0) {
        return {
          success: false,
          message: '未找到转换结果'
        };
      }
      
      return {
        success: true,
        data: result.rows[0]
      };
    } catch (error) {
      console.error('获取转换结果失败:', error);
      return {
        success: false,
        error: error.message
      };
    }
  }

  // 清理和美化HTML内容
  cleanHtml(html) {
    // 移除Word特有的标签和不必要的属性，但保留基本格式
    let cleanedHtml = html
      .replace(/<o:p[^>]*>.*?<\/o:p>/g, '') // 移除Word特有的标签
      .replace(/<\?xml[^>]*>/g, '') // 移除XML声明
      .replace(/<!--\[if[^>]*>.*?<!\[endif\]-->/g, '') // 移除条件注释
      .replace(/mso-[^;]+;?/g, '') // 移除Microsoft Office特有的CSS属性
      .replace(/font-family:[^;]*;?/g, '') // 移除字体设置，使用统一字体
      .replace(/font-size:[^;]*;?/g, '') // 移除字体大小设置
      .replace(/margin:[^;]*;?/g, '') // 移除边距设置
      .replace(/padding:[^;]*;?/g, '') // 移除内边距设置
      .replace(/style="[^"]*"/g, '') // 移除内联样式
      .replace(/class="[^"]*"/g, '') // 移除class属性
      .replace(/\s+/g, ' ') // 合并多个空格
      .trim();

    // 处理空段落
    cleanedHtml = cleanedHtml.replace(/<p>\s*<\/p>/g, '<p>&nbsp;</p>');
    
    // 处理列表项
    cleanedHtml = cleanedHtml.replace(/<p>([•·▪▫‣⁃])\s*(.*?)<\/p>/g, '<li>$2</li>');
    cleanedHtml = cleanedHtml.replace(/<p>(\d+\.)\s*(.*?)<\/p>/g, '<li>$2</li>');
    
    // 将连续的li包装在ul中
    cleanedHtml = cleanedHtml.replace(/(<li>.*?<\/li>)(\s*<li>.*?<\/li>)*/g, function(match) {
      return '<ul>' + match + '</ul>';
    });

    // 添加基本的CSS样式来改善显示效果
    const styledHtml = `
      <style>
        .document-content {
          font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Microsoft YaHei', sans-serif;
          line-height: 1.8;
          color: #333;
          max-width: 100%;
          font-size: 16px;
        }
        
        .document-title {
          font-size: 32px;
          font-weight: 700;
          color: #1890ff;
          text-align: center;
          margin: 0 0 32px 0;
          padding-bottom: 16px;
          border-bottom: 3px solid #1890ff;
        }
        
        .document-content h1, .document-content h2, .document-content h3, 
        .document-content h4, .document-content h5, .document-content h6 {
          color: #1890ff;
          margin-top: 32px;
          margin-bottom: 16px;
          font-weight: 600;
          line-height: 1.4;
        }
        
        .document-content h1 { 
          font-size: 28px; 
          border-bottom: 2px solid #e8e8e8; 
          padding-bottom: 12px; 
        }
        .document-content h2 { 
          font-size: 24px; 
          border-bottom: 1px solid #f0f0f0;
          padding-bottom: 8px;
        }
        .document-content h3 { font-size: 20px; }
        .document-content h4 { font-size: 18px; }
        .document-content h5 { font-size: 16px; }
        .document-content h6 { font-size: 14px; }
        
        .document-content p {
          margin-bottom: 16px;
          text-align: justify;
          text-justify: inter-ideograph;
        }
        
        .document-content ul, .document-content ol {
          margin: 16px 0;
          padding-left: 32px;
        }
        
        .document-content li {
          margin-bottom: 8px;
          line-height: 1.6;
        }
        
        .document-content ul li {
          list-style-type: disc;
        }
        
        .document-content ol li {
          list-style-type: decimal;
        }
        
        .document-content table {
          width: 100%;
          border-collapse: collapse;
          margin: 24px 0;
          border: 1px solid #d9d9d9;
          border-radius: 6px;
          overflow: hidden;
        }
        
        .document-content th, .document-content td {
          border: 1px solid #d9d9d9;
          padding: 12px 16px;
          text-align: left;
        }
        
        .document-content th {
          background-color: #fafafa;
          font-weight: 600;
          color: #262626;
        }
        
        .document-content tr:nth-child(even) {
          background-color: #fafafa;
        }
        
        .document-content blockquote {
          border-left: 4px solid #1890ff;
          margin: 24px 0;
          padding: 16px 24px;
          background-color: #f6f8fa;
          font-style: italic;
          border-radius: 0 6px 6px 0;
        }
        
        .document-content code {
          background-color: #f6f8fa;
          padding: 4px 8px;
          border-radius: 4px;
          font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
          font-size: 0.9em;
          color: #d73a49;
        }
        
        .document-content pre {
          background-color: #f6f8fa;
          padding: 16px;
          border-radius: 8px;
          overflow-x: auto;
          margin: 24px 0;
          border: 1px solid #e1e4e8;
        }
        
        .document-content pre code {
          background: none;
          padding: 0;
          color: #24292e;
        }
        
        .document-content img {
          max-width: 100%;
          height: auto;
          border-radius: 8px;
          box-shadow: 0 4px 12px rgba(0,0,0,0.15);
          margin: 24px 0;
          display: block;
        }
        
        .document-content strong, .document-content b {
          font-weight: 600;
          color: #262626;
        }
        
        .document-content em, .document-content i {
          font-style: italic;
          color: #595959;
        }
        
        .document-content a {
          color: #1890ff;
          text-decoration: none;
          border-bottom: 1px solid transparent;
          transition: border-color 0.3s ease;
        }
        
        .document-content a:hover {
          border-bottom-color: #1890ff;
        }
        
        .document-content hr {
          border: none;
          height: 2px;
          background: linear-gradient(to right, #1890ff, transparent);
          margin: 32px 0;
        }
        
        /* 响应式设计 */
        @media (max-width: 768px) {
          .document-content {
            font-size: 14px;
            line-height: 1.6;
          }
          
          .document-title {
            font-size: 24px;
          }
          
          .document-content h1 { font-size: 22px; }
          .document-content h2 { font-size: 20px; }
          .document-content h3 { font-size: 18px; }
          .document-content h4 { font-size: 16px; }
          
          .document-content ul, .document-content ol {
            padding-left: 24px;
          }
          
          .document-content th, .document-content td {
            padding: 8px 12px;
          }
        }
      </style>
      <div class="document-content">
        ${cleanedHtml}
      </div>
    `;

    return styledHtml;
  }

  // HTML转义
  escapeHtml(text) {
    const map = {
      '&': '&amp;',
      '<': '&lt;',
      '>': '&gt;',
      '"': '&quot;',
      "'": '&#039;'
    };
    return text.replace(/[&<>"']/g, (m) => map[m]);
  }
}

module.exports = new DocumentConversionService();